<template>
  <div class="signature-pad-container">
    <!-- 标题区域 -->
    <div class="mb-8 text-center slide-up">
      <span style="max-width: 100%; color: #4e5969; font-size: 14px">签名</span>
      <p
        style="
          max-width: 100%;
          color: #4e5969;
          font-size: 14px;
          margin-top: -0px;
        "
        >使用鼠标或触摸设备在下方区域签名，完成后可保存为图片</p
      >
    </div>

    <!-- 签名板卡片 -->
    <div
      class="bg-white rounded-xl shadow-card p-6 mb-8 transition-all duration-300 hover:shadow-card-hover slide-up"
      style="animation-delay: 0.1s"
    >
      <!-- 签名区域 -->
      <div class="mb-6">
        <div
          class="border border-neutral-200 rounded-lg overflow-hidden bg-white mb-4 canvas-shadow"
        >
          <canvas
            ref="signatureCanvas"
            class="w-full h-[240px] md:h-[300px] bg-neutral-50 cursor-crosshair"
          ></canvas>
        </div>
        <p
          style="
            max-width: 100%;
            color: #4e5969;
            font-size: 14px;
            margin-top: 10px;
          "
          >提示: 使用鼠标或触摸设备在画布上签名</p
        >
      </div>

      <!-- 操作按钮 -->
      <div class="withFlexRight">
        <a-space>
          <a-button type="dashed" @click="undo" :disabled="!canUndo">
            <template #icon>
              <icon-undo />
            </template>
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>撤销</template>
          </a-button>
          <a-button type="dashed" @click="clear" :disabled="!hasSignature">
            <template #icon> <icon-eraser /> </template>
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>清除</template>
          </a-button>
          <a-button
            type="primary"
            @click="saveSignature"
            :disabled="!hasSignature"
          >
            <template #icon> <icon-download /> </template>
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>保存</template>
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 预览区域 -->
    <div
      v-if="showPreview"
      class="mb-8 bg-white rounded-xl shadow-card p-6 slide-up"
      style="animation-delay: 0.2s"
    >
      <h2 class="text-xl font-semibold text-neutral-700 mb-4">签名预览</h2>
      <div class="flex flex-col md:flex-row gap-6 items-center">
        <div
          class="w-full md:w-1/2 rounded-lg overflow-hidden border border-neutral-200 canvas-shadow"
        >
          <img :src="signatureDataURL" alt="签名预览" class="w-full h-auto" />
        </div>
        <div class="w-full md:w-1/2 space-y-4">
          <!--          <div class="p-4 bg-neutral-50 rounded-lg">-->
          <!--            <div class="text-sm text-neutral-500 mb-1">签名信息</div>-->
          <!--            <div class="flex items-center gap-3">-->
          <!--              <div-->
          <!--                class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center"-->
          <!--              >-->
          <!--                <i class="fa-solid fa-signature text-primary text-xl"></i>-->
          <!--              </div>-->
          <!--              <div>-->
          <!--                <div class="font-medium text-neutral-700">电子签名</div>-->
          <!--                <div class="text-sm text-neutral-500">{{ signatureSize }}</div>-->
          <!--              </div>-->
          <!--            </div>-->
          <!--          </div>-->
          <!--          <div class="flex gap-3">-->
          <!--            <button-->
          <!--              @click="downloadSignature"-->
          <!--              class="btn-hover-effect flex-1 px-4 py-2.5 bg-primary text-white rounded-lg flex items-center justify-center gap-2"-->
          <!--            >-->
          <!--              <i class="fa-solid fa-download"></i>-->
          <!--              <span>下载</span>-->
          <!--            </button>-->
          <!--            <button-->
          <!--              @click="resetSignature"-->
          <!--              class="btn-hover-effect flex-1 px-4 py-2.5 bg-white border border-neutral-200 text-neutral-600 rounded-lg flex items-center justify-center gap-2"-->
          <!--            >-->
          <!--              <i class="fa-solid fa-plus"></i>-->
          <!--              <span>新签名</span>-->
          <!--            </button>-->
          <!--          </div>-->
        </div>
      </div>
    </div>

    <!-- 上传结果区域 -->
    <div
      v-if="showUploadResult"
      class="mb-8 bg-white rounded-xl shadow-card p-6 slide-up"
      style="animation-delay: 0.3s"
    >
      <div class="flex items-start gap-4">
        <div
          :class="
            uploadSuccess
              ? 'w-12 h-12 rounded-full bg-success/10 text-success flex items-center justify-center mt-1'
              : 'w-12 h-12 rounded-full bg-danger/10 text-danger flex items-center justify-center mt-1'
          "
        >
          <i
            :class="
              uploadSuccess
                ? 'fa-solid fa-check text-xl'
                : 'fa-solid fa-times text-xl'
            "
          ></i>
        </div>
        <!--        <div class="flex-1">-->
        <!--          <h2 class="text-xl font-semibold text-neutral-700 mb-2">{{-->
        <!--            uploadResultTitle-->
        <!--          }}</h2>-->
        <!--          <p class="text-neutral-600 mb-4">{{ uploadResultMessage }}</p>-->
        <!--          <div-->
        <!--            v-if="uploadSuccess && uploadResultImage"-->
        <!--            class="mb-4 rounded-lg overflow-hidden border border-neutral-200 max-w-xs canvas-shadow"-->
        <!--          >-->
        <!--            <img-->
        <!--              :src="uploadResultImage"-->
        <!--              alt="上传的签名"-->
        <!--              class="w-full h-auto"-->
        <!--            />-->
        <!--          </div>-->
        <!--          <div class="flex gap-3 justify-end">-->
        <!--            <button-->
        <!--              @click="closeUploadResult"-->
        <!--              class="btn-hover-effect px-5 py-2.5 bg-white border border-neutral-200 text-neutral-600 rounded-lg flex items-center gap-2"-->
        <!--            >-->
        <!--              <i class="fa-solid fa-check"></i>-->
        <!--              <span>完成</span>-->
        <!--            </button>-->
        <!--          </div>-->
        <!--        </div>-->
      </div>
    </div>

    <!-- 加载中模态框 -->
    <div
      v-if="isLoading"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 fade-in"
    >
      <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4">
        <div class="flex flex-col items-center">
          <div
            class="w-16 h-16 border-4 border-primary/30 border-t-primary rounded-full animate-spin mb-4"
          ></div>
          <h3 class="text-lg font-medium text-neutral-700 mb-2">{{
            loadingText
          }}</h3>
          <p class="text-neutral-500 text-center">{{ loadingSubtext }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, onUnmounted, watch } from 'vue';
  import axios from 'axios';
  // 组件状态
  const signatureCanvas = ref(null);
  const ctx = ref(null);
  const isDrawing = ref(false);
  const lastX = ref(0);
  const lastY = ref(0);
  const signatureHistory = ref([]); // 存储签名历史，用于撤销操作
  const showPreview = ref(false);
  const signatureDataURL = ref('');
  const signatureSize = ref('大小: --');
  const showUploadResult = ref(false);
  const uploadSuccess = ref(false);
  const uploadResultTitle = ref('');
  const uploadResultMessage = ref('');
  const uploadResultImage = ref('');
  const isLoading = ref(false);
  const loadingText = ref('处理中...');
  const loadingSubtext = ref('请稍候，我们正在处理您的请求');

  // 计算属性
  const hasSignature = ref(false);
  const canUndo = ref(false);

  const props = defineProps({
    imgUrl: String,
  });
  const emit = defineEmits(['update:imgUrl', 'refresh']);
  // 初始化
  onMounted(() => {
    // 获取Canvas上下文
    ctx.value = signatureCanvas.value.getContext('2d');

    // 设置Canvas样式
    ctx.value.lineJoin = 'round';
    ctx.value.lineCap = 'round';
    ctx.value.lineWidth = 3;
    ctx.value.strokeStyle = '#165DFF'; // 使用主色调作为笔触颜色

    // 设置Canvas尺寸
    resizeCanvas();

    // 添加事件监听
    addEventListeners();

    // 监听窗口大小变化
    window.addEventListener('resize', resizeCanvas);
  });

  // onUnmounted(() => {
  //   // 移除事件监听
  //   removeEventListeners();
  //   window.removeEventListener('resize', resizeCanvas);
  // });

  // 设置Canvas尺寸
  function resizeCanvas() {
    const container = signatureCanvas.value.parentElement;
    const dpr = window.devicePixelRatio || 1;
    signatureCanvas.value.width = container.clientWidth * dpr;
    signatureCanvas.value.height = signatureCanvas.value.offsetHeight * dpr;
    ctx.value.scale(dpr, dpr);
    ctx.value.clearRect(
      0,
      0,
      signatureCanvas.value.width,
      signatureCanvas.value.height
    );
    redrawSignature();
  }

  // 添加事件监听
  function addEventListeners() {
    // 鼠标事件
    signatureCanvas.value.addEventListener('mousedown', startDrawing);
    signatureCanvas.value.addEventListener('mousemove', draw);
    signatureCanvas.value.addEventListener('mouseup', stopDrawing);
    signatureCanvas.value.addEventListener('mouseout', stopDrawing);

    // 触摸事件
    signatureCanvas.value.addEventListener('touchstart', handleTouchStart);
    signatureCanvas.value.addEventListener('touchmove', handleTouchMove);
    signatureCanvas.value.addEventListener('touchend', stopDrawing);
    signatureCanvas.value.addEventListener('touchcancel', stopDrawing);
  }

  // 移除事件监听
  function removeEventListeners() {
    // 鼠标事件
    signatureCanvas.value.removeEventListener('mousedown', startDrawing);
    signatureCanvas.value.removeEventListener('mousemove', draw);
    signatureCanvas.value.removeEventListener('mouseup', stopDrawing);
    signatureCanvas.value.removeEventListener('mouseout', stopDrawing);

    // 触摸事件
    signatureCanvas.value.removeEventListener('touchstart', handleTouchStart);
    signatureCanvas.value.removeEventListener('touchmove', handleTouchMove);
    signatureCanvas.value.removeEventListener('touchend', stopDrawing);
    signatureCanvas.value.removeEventListener('touchcancel', stopDrawing);
  }

  // 开始绘制（鼠标）
  function startDrawing(e) {
    isDrawing.value = true;
    const { offsetX, offsetY } = getCanvasCoordinates(e);
    [lastX.value, lastY.value] = [offsetX, offsetY];
    signatureHistory.value.push([]); // 开始新的笔画
  }

  // 开始绘制（触摸）
  function handleTouchStart(e) {
    e.preventDefault();
    const touch = e.touches[0];
    const { offsetX, offsetY } = getCanvasCoordinates(touch);
    isDrawing.value = true;
    [lastX.value, lastY.value] = [offsetX, offsetY];
    signatureHistory.value.push([]); // 开始新的笔画
  }

  // 绘制（鼠标和触摸）
  function draw(e) {
    if (!isDrawing.value) return;
    const { offsetX, offsetY } = getCanvasCoordinates(e);
    ctx.value.beginPath();
    ctx.value.moveTo(lastX.value, lastY.value);
    ctx.value.lineTo(offsetX, offsetY);
    ctx.value.stroke();
    [lastX.value, lastY.value] = [offsetX, offsetY];

    // 记录当前笔画的点
    const currentStroke =
      signatureHistory.value[signatureHistory.value.length - 1];
    currentStroke.push({ x: offsetX, y: offsetY });

    // 更新按钮状态
    updateButtonStates();
  }

  // 绘制（触摸）
  function handleTouchMove(e) {
    e.preventDefault();
    if (!isDrawing.value) return;
    const touch = e.touches[0];
    const { offsetX, offsetY } = getCanvasCoordinates(touch);
    ctx.value.beginPath();
    ctx.value.moveTo(lastX.value, lastY.value);
    ctx.value.lineTo(offsetX, offsetY);
    ctx.value.stroke();
    [lastX.value, lastY.value] = [offsetX, offsetY];

    // 记录当前笔画的点
    const currentStroke =
      signatureHistory.value[signatureHistory.value.length - 1];
    currentStroke.push({ x: offsetX, y: offsetY });

    // 更新按钮状态
    updateButtonStates();
  }

  // 结束绘制
  function stopDrawing() {
    isDrawing.value = false;
  }

  // 撤销上一步
  function undo() {
    if (signatureHistory.value.length > 0) {
      signatureHistory.value.pop(); // 移除最后一笔
      redrawSignature();
      updateButtonStates();
    }
  }

  // 清除所有签名
  function clear() {
    ctx.value.clearRect(
      0,
      0,
      signatureCanvas.value.width,
      signatureCanvas.value.height
    );
    signatureHistory.value = [];
    updateButtonStates();
  }

  // 重绘签名
  function redrawSignature() {
    ctx.value.clearRect(
      0,
      0,
      signatureCanvas.value.width,
      signatureCanvas.value.height
    );
    signatureHistory.value.forEach((stroke) => {
      if (stroke.length > 0) {
        ctx.value.beginPath();
        ctx.value.moveTo(stroke[0].x, stroke[0].y);
        stroke.forEach((point) => {
          ctx.value.lineTo(point.x, point.y);
        });
        ctx.value.stroke();
      }
    });
  }

  // 获取Canvas坐标（处理缩放和设备像素比）
  function getCanvasCoordinates(e) {
    const rect = signatureCanvas.value.getBoundingClientRect();
    const x =
      (e.clientX - rect.left) / (rect.width / signatureCanvas.value.width);
    const y =
      (e.clientY - rect.top) / (rect.height / signatureCanvas.value.height);
    return { offsetX: x, offsetY: y };
  }

  // 更新按钮状态
  function updateButtonStates() {
    hasSignature.value =
      signatureHistory.value.length > 0 &&
      signatureHistory.value.some((stroke) => stroke.length > 0);
    canUndo.value = signatureHistory.value.length > 0;
  }

  // 保存签名为图片
  function saveSignature() {
    signatureDataURL.value = signatureCanvas.value.toDataURL('image/png');
    showPreview.value = true;

    // 计算图片大小
    const byteCharacters = atob(signatureDataURL.value.split(',')[1]);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const sizeInKB = (byteArray.byteLength / 1024).toFixed(2);
    signatureSize.value = `大小: ${sizeInKB} KB`;
    uploadSignature();
  }

  // 下载图片
  function downloadSignature() {
    const link = document.createElement('a');
    link.href = signatureDataURL.value;
    link.download = 'signature.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 重置签名
  function resetSignature() {
    clear();
    showPreview.value = false;
    showUploadResult.value = false;
  }

  // 上传签名
  async function uploadSignature() {
    try {
      showLoading('上传中', '正在将签名上传到服务器...');
      const dataURL = signatureCanvas.value.toDataURL('image/png');
      const blob = await dataURLToBlob(dataURL);
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', blob, 'signature.png');
      const url = import.meta.env.VITE_API_BASE_URL + 'global/upload';
      const response = await axios.post(url, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        // 可以添加进度事件处理
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`上传进度: ${percentCompleted}%`);
        },
      });
      emit('update:imgUrl', response.data[0]);
      hideLoading();
      showUploadResult.value = true;
      uploadSuccess.value = true;
      uploadResultTitle.value = '上传成功';
      uploadResultMessage.value = '签名已成功上传到服务器';
      uploadResultImage.value = dataURL;
    } catch (error) {
      hideLoading();
      showUploadResult.value = true;
      uploadSuccess.value = false;
      uploadResultTitle.value = '上传失败';
      uploadResultMessage.value = '签名上传过程中出现错误，请重试';
      console.error('上传失败:', error);
    }
  }

  // 关闭上传结果
  function closeUploadResult() {
    showUploadResult.value = false;
  }

  // 数据URL转Blob
  function dataURLToBlob(dataURL) {
    return new Promise((resolve) => {
      const byteString = atob(dataURL.split(',')[1]);
      const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);

      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }

      resolve(new Blob([ab], { type: mimeString }));
    });
  }

  // 模拟上传（实际应用中应替换为真实API调用）
  function simulateUpload(blob) {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟API响应
        resolve({ success: true });
      }, 1500);
    });
  }

  // 显示加载中
  function showLoading(title, message) {
    isLoading.value = true;
    loadingText.value = title;
    loadingSubtext.value = message;
  }

  // 隐藏加载中
  function hideLoading() {
    isLoading.value = false;
  }
</script>

<style scoped>
  .signature-pad-container {
    font-family: 'Inter', system-ui, sans-serif;
  }

  .canvas-shadow {
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05), 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .btn-hover-effect {
    transition: all 0.3s ease;
    transform: scale(1);
  }

  .btn-hover-effect:hover {
    transform: scale(1.02);
  }

  .btn-hover-effect:active {
    transform: scale(0.98);
  }

  .fade-in {
    animation: fadeIn 0.3s ease-in-out;
  }

  .slide-up {
    animation: slideUp 0.4s ease-out;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes slideUp {
    from {
      transform: translateY(20px);
      opacity: 0;
    }
    to {
      transform: translateY(0);
      opacity: 1;
    }
  }
  .withFlexRight {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
</style>
